<template>
	<div class="resource-dots-video">
		<!-- 视频区域 -->
		<div class="video-box" :style="{'height':height+20+'px'}">
			<div class="old-video">
				<div class="video-title">原视频预览</div>
				<div ref="player" id="player" />
			</div>
			<div class="video-margin" />
			<div class="dot-video">
				<div class="video-title">打点片段预览</div>
				<div ref="dotPlayer" />
			</div>
		</div>
		<!-- 打点步骤 -->
		<div class="video-step-box">
			<div class="step-1">
				<!-- 第一步打点位置 -->
				<div class="step-title">
					<span v-if="type!=='edit'">第一步：</span>选择打点位置
					<span class="step-title-tip">提示: 您可拖动进度条设置打点位置，也可修改起始时间设置打点位置</span>
				</div>
				<div class="step-title">打点起始位置</div>
				<div class="slider-box">
					<el-slider
						v-model="playerValue"
						range
						:max="playerDuration"
						:marks="marks"
						@change="changeTime"
					/>
				</div>
				<div class="step-title">打点起始时间</div>
				<div>
					<el-time-picker
						v-model="playerStartTimeFormat"
						value-format="HH:mm:ss"
						:clearable="false"
						:picker-options="{
							format:'HH:mm:ss',
							selectableRange:`00:00:00 - ${this.getHMS(playerEndTime-1)}`
						}"
						placeholder="开始时间"
						@change="pickerChange"
					/>
					<el-time-picker
						v-model="playerEndTimeFormat"
						:clearable="false"
						value-format="HH:mm:ss"
						:picker-options="{
							format:'HH:mm:ss',
							selectableRange:`${this.getHMS(playerStartTime+1)} - ${this.getHMS(playerDuration)}`
						}"
						placeholder="结束时间"
						@change="pickerChange"
					/>
				</div>
			</div>
			<div class="video-margin" />
			<div class="step-2" v-if="type!=='edit'">
				<!-- 第二步打点位置 -->
				<div class="step-title">第二步：关联打点内容</div>
				<choice-knowledge ref="knowledgeRef" v-bind="$attrs" :show-search="true" />
				<choice-question ref="questionRef" v-bind="$attrs" :show-search="true" />
				<el-button
					class="save-btn"
					size="small"
					type="primary"
					:loading="saveLoading"
					@click="onSavePoint"
				>
					保存
				</el-button>
			</div>
		</div>
	</div>
</template>
<script>
	const userData = User.getUser() || {};

    import coursewareApi from "@rc/apis/rc/courseware.mjs";
    import ChoiceKnowledge from "../choice-knowledge/index.vue"; //选择知识点
	import ChoiceQuestion from "../choice-question/index.vue"; //选择试题

	export default {
		name: "resource-dots-video",
		props: {
			vid: {
				type: String,
				required: true
			},
			resourceId: {
				type: String,
				required: true
			},
            type:{
                type:String,
                default: 'add'
            },
            allowFullscreen:{//是否允许全屏播放
                type: Boolean,
                default: true
            },
            height:{
                type:Number,
                default:400
            },
            startTime:{
                type: Number,
                default: 0
            },
            endTime:{
                type: Number,
                default: 0
            },
			polyvToken: {
				type: String,
                default: ''
			}
		},
		components: {
			ChoiceKnowledge,
			ChoiceQuestion
		},
		data() {
			return {
				player: null,
				dotPlayer: null,
				playerDuration: null,
				playerValue: [0, 0],
                playerStartTimeFormat:'00:00:00',
                playerEndTimeFormat:'00:00:00',
				playerStartTime: 0,
				playerEndTime: 0,
				resourceInfo: {},
                selectValue:[],
                saveLoading:false,
                baseOptions:{},
			};
		},
        computed:{
           marks(){//打点位置marks
                return {
                    [this.playerStartTime]:this.getHMS(this.playerStartTime)+'开始',
                    [this.playerEndTime]:this.getHMS(this.playerEndTime)+'结束'
                };
            }
        },
		watch: {
			vid: {
				async handler(val) {
					if (val) {
						// 加载保利威js资源函数，为避免js加载完，节点还没渲染完成，需要放在节点渲染完成后
						await this.loadPlayerScript();
						this.renderLive();
					} else {
						this.$alert("缺失资源id参数，请确认资源信息是否正常", "提示");
					}
				},
				immediate: true
			}
		},
		destroyed() {
			this.player && this.player.destroy();
		},
		methods: {
			/**
			 * 加载保利威js资源函数
			 * @return Promise 加载的结果
			 */
			loadPlayerScript() {
				return new Promise((rs) => {
					if (window.polyvPlayer) {
						// window对象已经被挂载上保利威实例，无需二次加载
						this.isLoadJs = true;
						rs();
					} else {
						// 第一次加载保利威js
						const myScript = document.createElement("script");
						myScript.setAttribute("src", "//player.polyv.net/script/player.js");
						document.body.appendChild(myScript);
						myScript.onload = () => {
							this.isLoadJs = true;
							rs();
						};
					}
				});
			},
			renderLive() {
				const { polyvToken } = this;
				// 公共全局配置
				const baseOptions = {
					width: "100%",
					height: this.height,
                    ban_history_time:'on',
                    allowFullscreen:this.allowFullscreen,
					hideSwitchPlayer: true, // 隐藏flash,h5播放器切换按钮
					code: userData.userName + userData.eeNo || new Date().getTime(), // 跑马灯
					playsafe(vid = "", next) {
						if (polyvToken) {
							next(polyvToken);
						} else {
							Http.callService({
								url: "fs/polyv/token/get",
								data: {
									videoId: vid.trim(),
									type: "R"
								}
							}).success((result) => {
								next(result.token);
							});
						}
					}
				};
                this.baseOptions = baseOptions;
				// 第一次初始化视频，生成视频实例
				this.player = window.polyvPlayer({
					wrap: this.$refs.player,
					vid: this.vid, //云点播平台的视频唯一id。
					...baseOptions
				});
                if(this.type==='edit'||this.type==='reset'){
                    this.playerValue = [ this.startTime, this.endTime];
                    this.playerStartTime = this.startTime;
				    this.playerEndTime = this.endTime;
                    this.playerStartTimeFormat = this.getHMS(this.startTime);
                    this.playerEndTimeFormat = this.getHMS(this.endTime);
                    this.createLive();
                }else{
                    this.dotPlayer = window.polyvPlayer({
                        wrap: this.$refs.dotPlayer,
                        vid: this.vid, //云点播平台的视频唯一id。
                        ...baseOptions,
				    });
                }
				this.getDurationTime();
			},
			//获取视频时长
			getDurationTime() {
				this.player.on("s2j_onPlayerInitOver", () => {
					const duration = this.player.j2s_getDuration();
                    this.playerDuration = duration-1;
                    if(this.type==='add'){//新增
                        this.playerValue = [0, this.playerDuration];
                        this.playerStartTime = 0;
				        this.playerEndTime = this.playerDuration;
                        this.playerStartTimeFormat = '00:00:00';
                        this.playerEndTimeFormat = this.getHMS(this.playerDuration);
                        this.createLive();
                    } else {
                         this.playerValue = [ this.startTime, this.endTime];
                    }
				});
			},
			debounce(func, delay = 200) {
				let time = null;
				return () => {
					if (time !== null) {
						clearTimeout(time);
					}
					time = setTimeout(() => {
						func.call(this);
					}, delay);
				};
			},
            // 根据秒数转换成对应的时分秒
            getHMS (time) {
                if(!time){
                    return '00:00:00';
                }
                const hour = parseInt(time / 3600) < 10 ? '0' + parseInt(time / 3600) : parseInt(time / 3600);
                const min = parseInt(time % 3600 / 60) < 10 ? '0' + parseInt(time % 3600 / 60) : parseInt(time % 3600 / 60);
                const sec = parseInt(time % 3600 % 60) < 10 ? '0' + parseInt(time % 3600 % 60) : parseInt(time % 3600 % 60);
                return hour + ':' + min + ':' + sec;
            },
            //时分秒转秒
            getSecond(hms){
                let arr = hms.split(":");
                return Number(arr[0])*3600+Number(arr[1])*60+Number(arr[2]);
            },
            pickerChange(){
                this.playerValue = [this.getSecond(this.playerStartTimeFormat),this.getSecond(this.playerEndTimeFormat)];
                this.playerStartTime = this.playerValue[0];
				this.playerEndTime = this.playerValue[1];
                this.debounce(this.createLive, 500)();
            },
            changeTime(val){
                if(val[0]===val[1]) {//开始时间和结束时间相等
                    this.playerStartTime = val[0];
				    this.playerEndTime = val[1]+1;
                } else if (val[0] > val[1]) {//结束时间大于开始时间
                    this.playerStartTime = val[0];
                    this.playerEndTime = val[1];
                } else {
                    this.playerStartTime = val[0];
				    this.playerEndTime = val[1];
                }
                if(val[0]===this.playerDuration) {
                    this.playerStartTime = val[0]-1;
				    this.playerEndTime = this.playerDuration;
                }
                this.playerValue = [this.playerStartTime,this.playerEndTime];

                this.playerStartTimeFormat = this.getHMS(this.playerStartTime);
                this.playerEndTimeFormat = this.getHMS(this.playerEndTime);
                this.debounce(this.createLive, 500)();
            },
			createLive() {
				if (this.dotPlayer) {
					this.dotPlayer.destroy();
				}
				this.$nextTick(() => {
					this.dotPlayer = polyvPlayer({
                        ...this.baseOptions,
						wrap: this.$refs.dotPlayer,
						vid: this.vid, //云点播平台的视频唯一id。
						start: this.playerStartTime,
						end:  this.playerEndTime
					});
				});
			},
            //保存视频打点
            onSavePoint(){
                const {knowledgeIdList,dotDescription} = this.$refs.knowledgeRef.api_getKnowledgeList();
                const {questionIdList} = this.$refs.questionRef.api_getQuestionList();
                //如果没有选择知识点或试题无法进行保存操作
                if(!knowledgeIdList.length && !questionIdList.length){
                    this.$message.warning("请关联知识点或试题");
				    return;
                }
                this.saveLoading = true;
                coursewareApi.addResourceVideoDot({
					data: {
						resourceId: this.resourceId,
                        startTime:this.playerStartTime,
                        endTime:this.playerEndTime,
                        knowledgeIdList,
                        questionIdList,
                        dotDescription:dotDescription
					},
					success: () => {
                        this.$message.success("添加打点成功");
						//刷新视频
                        this.$emit('save-success',{
                            startTime:this.playerStartTime,
                            endTime:this.playerEndTime,
                            playerDuration:this.playerDuration
                        });
					},
					complete: () => {
						this.saveLoading = false;
					}
				});
            },
            api_getVidTime(){
                return {
                    startTime:this.playerStartTime,
                    endTime:this.playerEndTime,
                };
            }
		}
	};
</script>
<style src="./index.less" scoped/>
